package com.open.pingban.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ProgressBar;

import com.open.pingban.MainActivity;
import com.open.pingban.R;
import com.open.pingban.activity.VideoPlayerActivity;
import com.open.pingban.adapter.VideoAdapter;
import com.open.pingban.mode.VideoData;
import com.open.pingban.presenter.IVideoContract;
import com.open.pingban.presenter.VideoPresenter;
import com.open.pingban.utils.OPENLOG;
import com.open.pingban.utils.OpenFileUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * VOD视频点播界面.
 */
public class VodVideoStreamingFragment extends BaseView implements IVideoContract.IVideoView {

    private static final int VIDEO_ITEM_NUM = 30;
    private static final int VIDEO_PAGE_DEFAULT = 1;

    @InjectView(R.id.search_et)
    EditText searchEt;
    @InjectView(R.id.progressBar)
    ProgressBar progressBar;

    private int mVideoPage = VIDEO_PAGE_DEFAULT;
    private VideoAdapter mVideoAdapter;
    private GridView mGridView;
    private IVideoContract.IVideoPresenter mVideoPresenter;
    private int getLastVisiblePosition = 0, lastVisiblePositionY = 0;

    public VodVideoStreamingFragment(Activity activity) {
        super(activity);
    }

    public static VodVideoStreamingFragment newInstance(Activity activity) {
        VodVideoStreamingFragment newFragment = new VodVideoStreamingFragment(activity);
        return newFragment;
    }

    private View mRootView;

    @Override
    public View onCreateView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_vod_video, null, false);
        ButterKnife.inject(this, rootView);
        mRootView = rootView;
        return rootView;
    }

    @Override
    public void onActivityCreated() {
        mVideoPresenter = new VideoPresenter(this);
        mGridView = (GridView) mRootView.findViewById(R.id.vod_video_gridview);
        mVideoAdapter = new VideoAdapter();
        mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mGridView.setAdapter(mVideoAdapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String url = mVideoAdapter.getVideos().get(position).getsFileName();
                if (!TextUtils.isEmpty(url)) {
                    ((MainActivity)getActivity()).stopAllVideoAndAudio(-1);
                    // 弹出播放视频的窗口(进行电影播放)
                    Intent intent = new Intent(getActivity(), VideoPlayerActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        String newUrl = OpenFileUtils.getOsDisplay(url);
                        OPENLOG.D("打开视频 ==> newUrl:" + newUrl);
                        intent.putExtra("play_addr", "" + newUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    startActivity(intent);
                }
            }
        });
        mGridView.setOnScrollListener(mOnScrollListener);
        updateNetWorkView();
    }

    @Override
    public void updateNetWorkView() {
        mUpdateHander.sendEmptyMessageDelayed(-250, 1400);
    }

    Handler mUpdateHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                mVideoPresenter.getVideoList("", mVideoPage, VIDEO_ITEM_NUM);
            } catch (Exception e) {
                OPENLOG.E("" + e.getMessage());
                e.printStackTrace();
            }
        }
    };

    AbsListView.OnScrollListener mOnScrollListener = new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                //滚动到底部
                if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                    View v = (View) view.getChildAt(view.getChildCount() - 1);
                    int[] location = new int[2];
                    v.getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标
                    int y = location[1];

                    if (view.getLastVisiblePosition() != getLastVisiblePosition && lastVisiblePositionY != y) {//第一次拖至底部
                        Log.d("hailongqiu", "拖动到底部了....");
                        getLastVisiblePosition = view.getLastVisiblePosition();
                        lastVisiblePositionY = y;
                        addMoreData();
                        return;
                    } else if (view.getLastVisiblePosition() == getLastVisiblePosition && lastVisiblePositionY == y) { //第二次拖至底部
                        Log.d("hailongqiu", "刷新了....");
                        addMoreData();
                    }
                    //未滚动到底部，第二次拖至底部都初始化
                    getLastVisiblePosition = 0;
                    lastVisiblePositionY = 0;
                }
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    };

    private void addMoreData() {
    }

    @OnClick({R.id.search_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_btn:
                String keyword = searchEt.getText().toString();
                if (!TextUtils.isEmpty(keyword)) {
                    loadDatasView(true);
                    mVideoPresenter.getVideoList(keyword, mVideoPage, VIDEO_ITEM_NUM);
                } else {
                    showMsg("请输入关键字");
                }
                break;
        }
    }

    private void loadDatasView(boolean b) {
        try {
            mGridView.setVisibility(b ? View.GONE : View.VISIBLE);
            progressBar.setVisibility(b ? View.VISIBLE : View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateVideoList(VideoData videoData) {
        int page = videoData.getResponse().getPage();
        int total = videoData.getResponse().getTotal();
        OPENLOG.D("total:" + total + " page:" + page);
        VideoData.Response response = videoData.getResponse();
        mVideoAdapter.setVideos(response.getData());
        loadDatasView(false);
    }

    @Override
    public void updateVideoFailure() {
        showMsg("获取视频失败");
        loadDatasView(false);
    }

}
